package org.argus.management.system.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.argus.common.core.exception.ServiceException;
import org.argus.common.core.enums.StatusEnum;
import org.argus.common.web.core.snowflake.SnowflakeIdGenerator;
import org.argus.management.common.SecurityUtils;
import org.argus.management.domain.User;
import org.argus.management.system.mapper.UserMapper;
import org.argus.management.system.model.SaveUserReq;
import org.argus.management.system.model.UpdateUserPasswordReq;
import org.argus.management.system.model.UserRoleBindReq;
import org.argus.management.system.model.UserSearchReq;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author 刘文/Cliff Liu
 * @Date 2024/4/24
 */
@Component
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SnowflakeIdGenerator idGenerator;

    public User getUserInfo(String username) {
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(User.class).eq(User::getUsername, username)
                .eq(User::getStatus, StatusEnum.NORMAL);
        return userMapper.selectOne(queryWrapper);
    }

    public Page<User> page(UserSearchReq req, Page page) {
        return userMapper.page(page, req);
    }

    @Transactional(rollbackFor = Exception.class)
    public void save(SaveUserReq req) {
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(User.class).eq(User::getUsername, req.getUsername());
        if (req.getId() != null) {
            queryWrapper.ne(User::getId, req.getId());
        }
        if (userMapper.selectOne(queryWrapper) != null) {
            throw new ServiceException("用户名已存在");
        }
        User user = new User();
        BeanUtils.copyProperties(req, user);
        // 新增
        if (req.getId() == null) {
            user.setId(idGenerator.nextId());
            userMapper.insert(user);
        }
        // 更新
        else {
            userMapper.updateById(user);
            // 删除原有关联
            userMapper.deleteUserDomainRelation(user.getId());
        }

        if (CollectionUtil.isNotEmpty(req.getDomainIds())) {
            userMapper.saveUserDomainRelation(user.getId(), req.getDomainIds());
        }
    }

    public void delete(List<Long> ids) {
        userMapper.updateUserStatus(ids, StatusEnum.DELETED);
    }

    public List<Long> userRoleIds(Long id) {
        return userMapper.userRoleIds(id);
    }

    public void updatePassword(UpdateUserPasswordReq updateReq) {
        LambdaUpdateWrapper<User> wrapper = Wrappers.lambdaUpdate(User.class).eq(User::getId, updateReq.getId())
            .set(User::getPassword, SecurityUtils.encryptPassword(updateReq.getPassword()));
        userMapper.update(null, wrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveUserRoleRel(UserRoleBindReq req) {
        userMapper.deleteUserRoleRel(req.getUserId());
        if (CollectionUtil.isNotEmpty(req.getRoleIds())) {
            userMapper.saveUserRoleRel(req.getUserId(), req.getRoleIds());
        }
    }
}
